#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<string>
#include<unordered_set>
#include<queue>
using namespace std;

class Solution
{
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList)
    {
        unordered_set<string> visit;
        unordered_set<string> hash(wordList.begin(), wordList.end());

        if (beginWord == endWord) return 1;
        if (hash.count(endWord) == 0) return 0;

        queue<string> q;
        q.push(beginWord);
        visit.insert(beginWord);

        int step = 1;
        while (!q.empty())
        {
            step++;
            int sz = q.size();

            while (sz--)
            {
                string t = q.front();
                q.pop();

                for (int i = 0; i < endWord.size(); i++)
                {
                    string tmp = t;
                    for (char ch = 'a'; ch <= 'z'; ch++)
                    {
                        tmp[i] = ch;
                        if (hash.count(tmp) == 1 && visit.count(tmp) == 0)
                        {
                            if (tmp == endWord) return step;
                            visit.insert(tmp);
                            q.push(tmp);
                        }
                    }
                }
            }
        }
        return 0;
    }
};